package com.hnust.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.impl.JWTParser;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Payload;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import java.util.*;

public class JwtToken {

    private static final String SECRET = "I AM IRON MAN";//密钥

    public static String createToken(String id,String password) throws Exception{
        Date date = new Date();
//        System.out.println("date:"+date);

        Calendar nowTime = Calendar.getInstance();
//        System.out.println("nowTime:"+nowTime);

        //过期时间设置为7天
        nowTime.add(Calendar.DAY_OF_WEEK,7);
        //nowTime.add(Calendar.SECOND,3);
//        System.out.println("nowTime:"+nowTime);

        Date expiresDate = nowTime.getTime();
//        System.out.println("expiresDate:"+expiresDate);

        String uuid = UUID.randomUUID().toString().replaceAll("-","");
//        System.out.println("uuid:"+uuid);

        Map<String,Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("typ","JWT");
        //map.put("org","循环再利用");
        //map.put("uuid",uuid);
        //map.put("time",expiresDate);

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("k1","v1");
//        jsonObject.put("k2","v2");
//        jsonObject.put("k3","v3");

//        String[] technology = {"spring","k8s","jwt"};

        String token = JWT.create()
                .withHeader(map)
//                .withArrayClaim("technology",technology)
                .withJWTId(uuid)
//                .withSubject(jsonObject.toString())
                .withClaim("id",id)
                .withClaim("password",password)
                .withExpiresAt(expiresDate)//过期时间
                .withIssuedAt(date)//签发时间
                .sign(Algorithm.HMAC256(SECRET));//密钥加密
        return token;
    }

    public static Map<String, String> verifyToken(String token) throws Exception{
        try {
            Map<String,String> map=new HashMap<>();
            JWTVerifier verifier =JWT.require(Algorithm.HMAC256(SECRET))
                    .build();
            DecodedJWT jwt = null;
            jwt = verifier.verify(token);

            //解码第二段
            String[] parts = token.split("[.]");
            String payloadJson = parts[1];
            String payload = StringUtils.newStringUtf8(Base64.decodeBase64(payloadJson));
            final JWTParser converter = new JWTParser();
            Payload payloadjson = converter.parsePayload(payload);
            String id=payloadjson.getClaims().get("id").asString();
            String password=payloadjson.getClaims().get("password").asString();
            map.put("id",id);
            map.put("password",password);
            //System.out.println("payloadjson:"+payloadjson.getClaims().get("id").asString());
            //System.out.println("第二段解析完成");
//
//            //jwt解析
//            System.out.println("JWT开始解析");
//            System.out.println(jwt.getHeaderClaim("org").asString());
//            System.out.println(jwt.getSubject());
//            System.out.println(jwt.getIssuedAt().toString());
//            System.out.println("JWT结束解析");

//            System.out.println("开始解码");
//            String header = token.split("[.]")[0];
//            System.out.println("header:"+header);

            return map;

        }catch (Exception e){
            // Exception in thread "main" java.lang.RuntimeException 过期token
            throw new RuntimeException("登陆凭证已过期，请重新登录.");
        }

    }
}


